package com.substation.ui.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.greenentity.Defect;
import com.greenentity.Eqpt;
import com.greenentity.Photo;
import com.greenentity.TourDefect;
import com.interfaces.ResponseListener;
import com.jessewu.library.SuperAdapter;
import com.jessewu.library.view.ViewHolder;
import com.previewlibrary.GPreviewBuilder;
import com.substation.R;
import com.substation.greendao.EqptDao;
import com.substation.ui.utils.BitmapDrawTextUtils;
import com.substation.ui.utils.RecyclerViewUtils;
import com.substation.ui.utils.XUtils;
import com.substation.utils.DateUtils;
import com.substation.utils.DialogUtils;
import com.substation.utils.GreenDaoManager;
import com.substation.utils.SPUtils;
import com.substation.utils.T;
import com.substation.utils.TestingUtils;
import com.yuyh.library.imgsel.ISNav;
import com.yuyh.library.imgsel.common.ImageLoader;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import butterknife.BindView;
import butterknife.OnClick;
import dmax.dialog.SpotsDialog;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

public class RemoveDefectActivity extends BaseListActivity {


    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.list)
    RecyclerView list;
    SuperAdapter<String> adapter;
    List<String> datas = new ArrayList<>();
    Defect defect;//巡视任务的消缺
    TourDefect tourDefect;//缺陷管理的消缺
    @BindView(R.id.description)
    TextView description;
    @BindView(R.id.eqpt)
    TextView eqpt;
    @BindView(R.id.person)
    TextView person;
    @BindView(R.id.find_time)
    TextView findTime;
    @BindView(R.id.process_person)
    EditText processPerson;
    @BindView(R.id.check_person)
    EditText checkPerson;
    @BindView(R.id.process_time)
    TextView processTime;
    @BindView(R.id.result)
    EditText result;
    @BindView(R.id.check_time)
    TextView checkTime;
    @BindView(R.id.conclusion)
    EditText conclusion;

    @Override
    protected int getMyListLayoutId() {
        return R.layout.activity_remove_defect;
    }

    @Override
    public RecyclerView.LayoutManager getLayoutManager() {
        return RecyclerViewUtils.getLinearLayoutManagerForHorizontal(context);
    }

    @Override
    protected void initView() {
        super.initView();
        // 自定义图片加载器
        ISNav.getInstance().init(new ImageLoader() {
            @Override
            public void displayImage(Context context, String path, ImageView imageView) {
                Glide.with(context).load(path).into(imageView);
            }
        });
        boolean work = (boolean) SPUtils.get(context, "work", false);//是否是从巡视过来的
        if (work) {
            defect = JSON.parseObject((String) SPUtils.get(context, "defect", ""), Defect.class);
            description.setText(defect.getDefectDesc());
            List<Eqpt> eqpts = GreenDaoManager.getInstance().getmDaoSession().getEqptDao().queryBuilder()
                    .where(EqptDao.Properties.EqptGuid.eq(defect.getEqptGuid())).list();
            eqpt.setText(eqpts.size() > 0 ? eqpts.get(0).getEqptName() : "未知设备");
            person.setText(defect.getDiscoveryUserIdvalue() + "");
            findTime.setText(defect.getDefectTime());
        } else {
            tourDefect = JSON.parseObject((String) SPUtils.get(context, "defect", ""), TourDefect.class);
            description.setText(tourDefect.getDefectDesc());
            List<Eqpt> eqpts = GreenDaoManager.getInstance().getmDaoSession().getEqptDao().queryBuilder()
                    .where(EqptDao.Properties.EqptGuid.eq(tourDefect.getEqptGuid())).list();
            eqpt.setText(eqpts.size() > 0 ? eqpts.get(0).getEqptName() : "未知设备");
            person.setText(tourDefect.getDiscoveryUserIdvalue() + "");
            findTime.setText(tourDefect.getDefectTime());
        }
        datas.add("");
        adapter.setData(datas);
        adapter.setEmptyDataView(R.layout.view_empty);
        refresh.setEnabled(false);
    }


    @Override
    public SuperAdapter getAdapter() {
        return adapter = new SuperAdapter<String>(R.layout.content_imge_horizontal) {
            @Override
            public void bindView(ViewHolder viewHolder, String s, final int i) {
                ImageView imageView = viewHolder.getView(R.id.imageView);
                ImageButton imageButton = viewHolder.getView(R.id.imageButton);
                if (i == datas.size() - 1) {
                    imageButton.setVisibility(View.GONE);
                    imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
                    Glide.with(context).load(R.mipmap.add_img).into(imageView);
                    imageView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            XUtils.choiseImg(RemoveDefectActivity.this, 9 - datas.size() + 1);
                        }
                    });
                } else {
                    imageButton.setVisibility(View.VISIBLE);
                    imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                    Glide.with(context).load(s).into(imageView);
                    imageView.setClickable(false);
                    imageButton.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            datas.remove(i);
                            adapter.notifyDataSetChanged();
                        }
                    });
                    viewHolder.getView(R.id.imageView).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            GPreviewBuilder.from(RemoveDefectActivity.this)
                                    .setData(XUtils.String2Image(datas))
                                    .setCurrentIndex(i)
                                    .setSingleFling(false)//是否在黑屏区域点击返回
                                    .setDrag(false)//是否禁用图片拖拽返回
                                    .setType(GPreviewBuilder.IndicatorType.Number)//指示器类型
                                    .start();//启动
                        }
                    });
                }
            }
        };
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_save, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.upload:
                String process = processPerson.getText().toString();
                String processT = processTime.getText().toString();
                String processR = result.getText().toString();
                String check = checkPerson.getText().toString();
                String checkT = checkTime.getText().toString();
                String checkR = conclusion.getText().toString();
                if (!TestingUtils.isEmpty(context, process, "处理人")) return true;
                if (!TestingUtils.isEmpty(context, processT, "处理时间")) return true;
                if (!TestingUtils.isEmpty(context, processR, "处理结果")) return true;
                if (!TestingUtils.isEmpty(context, check, "验收人")) return true;
                if (!TestingUtils.isEmpty(context, checkT, "验收时间")) return true;
                if (!TestingUtils.isEmpty(context, checkR, "验收结论")) return true;
                if (datas.size() == 1) {
                    showMsg("请上传照片");
                    return true;
                }

                if (defect != null) {
                    defect.setDealTime(processT + " 00:00:00");
                    defect.setDealUserName(process);
                    defect.setDealResult(processR);
                    defect.setCheckTime(checkT + " 00:00:00");
                    defect.setCheckUserName(check);
                    defect.setCheckConclusion(checkR);
                    defect.setDefectStatus("20");
                    GreenDaoManager.getInstance().getmDaoSession().getDefectDao().update(defect);
                } else if (tourDefect != null) {
                    tourDefect.setDealTime(processT + " 00:00:00");
                    tourDefect.setDealUserName(process);
                    tourDefect.setDealResult(processR);
                    tourDefect.setCheckTime(checkT + " 00:00:00");
                    tourDefect.setCheckUserName(check);
                    tourDefect.setCheckConclusion(checkR);
                    tourDefect.setDefectStatus("20");
                    GreenDaoManager.getInstance().getmDaoSession().getTourDefectDao().update(tourDefect);
                }
                datas.remove(datas.size() - 1);
                for (String s : datas) {
                    Photo photo = new Photo();
                    photo.setPhotoId(System.currentTimeMillis());
                    photo.setPhotoGuid(UUID.randomUUID().toString());
                    photo.setDefectGuid(defect == null ? tourDefect.getDefectGuid() : defect.getDefectGuid());
                    photo.setPhAdd(s);
                    photo.setPhState("新增");
                    photo.setPhName(s.substring(s.lastIndexOf("/") + 1));
                    GreenDaoManager.getInstance().getmDaoSession().getPhotoDao().insert(photo);
                }
                T.showLong(context, "保存成功");
                finish();
                return true;
            case android.R.id.home:
                DialogUtils.showMsgDialog(context, "是否返回", "您还未保存？是否直接退出？", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        finish();
                    }
                });
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == XUtils.REQUEST_CODE && resultCode == RESULT_OK && data != null) {// 图片选择结果回调
            List<String> pathList = data.getStringArrayListExtra("result");

            final SpotsDialog dialog = new SpotsDialog(context, "正在添加水印...");
            dialog.show();
            Observable.just(pathList).subscribeOn(Schedulers.io()).map(new Func1<List<String>, List<String>>() {
                @Override
                public List<String> call(List<String> list) {
                    return BitmapDrawTextUtils.createWater(context, (String) SPUtils.get(context, "substations", "") + " (消缺照片)"
                            , eqpt.getText().toString(), DateUtils.getNewTime(), list);
                }
            }).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<List<String>>() {
                @Override
                public void call(List<String> list) {
                    dialog.dismiss();
                    dialog.cancel();
                    datas.remove(datas.size() - 1);
                    datas.addAll(list);
                    if (datas.size() <= 8) {
                        datas.add("");
                    }
                    adapter.notifyDataSetChanged();
                }
            });

//            datas.remove(datas.size() - 1);
//            datas.addAll(pathList);
//            if (datas.size() <= 8) {
//                datas.add("");
//            }
//            adapter.notifyDataSetChanged();
        }
    }


    @OnClick({R.id.process_time, R.id.check_time})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.process_time:
                DialogUtils.showCalendarDialog(getFragmentManager(), "处理时间", new ResponseListener<String>() {
                    @Override
                    public void response(String data) {
                        processTime.setText(data);
                    }
                });
                break;
            case R.id.check_time:
                DialogUtils.showCalendarDialog(getFragmentManager(), "验收时间", new ResponseListener<String>() {
                    @Override
                    public void response(String data) {
                        checkTime.setText(data);
                    }
                });
                break;
        }
    }
}
